import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {
            return subRoot == null;
        }
        return equal(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    public boolean equal(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return root == subRoot;
        }

        return root.val == subRoot.val && equal(root.left, subRoot.left) && equal(root.right, subRoot.right);
    }
}

//先得到前序遍历序列，然后用KMP查找子序列（注意用lNull和rNull做子节点为空的标记）
class Solution1 {
    List<Integer> rootOrder = new ArrayList<>();
    List<Integer> subRootOrder = new ArrayList<>();
    int lNull = -100000, rNull = -100001;

    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        getPreOrder(root, rootOrder);
        getPreOrder(subRoot, subRootOrder);
        return kmp();
    }

    void getPreOrder(TreeNode root, List<Integer> result) {
        result.add(root.val);

        if (root.left == null) {
            result.add(lNull);
        } else {
            getPreOrder(root.left, result);
        }

        if (root.right == null) {
            result.add(rNull);
        } else {
            getPreOrder(root.right, result);
        }
    }

    boolean kmp() {
        int[] next = getNext();
        int j = 0;
        for (Integer each : rootOrder) {
            while (j > 0 && !subRootOrder.get(j).equals(each)) {
                j = next[j - 1];
            }
            if (subRootOrder.get(j).equals(each)) {
                j++;
                if (j == next.length) {
                    return true;
                }
            }
        }
        return false;
    }

    int[] getNext() {
        int[] next = new int[subRootOrder.size()];
        int i = 0, j = 1;
        while (j < next.length) {
            while (i > 0 && !subRootOrder.get(i).equals(subRootOrder.get(j))) {
                i = next[i - 1];
            }
            if (subRootOrder.get(i).equals(subRootOrder.get(j))) {
                i++;
            }
            next[j++] = i;
        }
        return next;
    }
}


//官方题解哈希法
class Solution2 {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        return true;
    }
}
